package com.lvy.hczn.transmit.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lvy.hczn.front.common.constant.Constants;
import com.lvy.hczn.front.common.constant.MqConstants;
import com.lvy.hczn.front.common.exception.UtilException;
import com.lvy.hczn.front.system.domain.business.*;
import com.lvy.hczn.front.system.service.WarehouseService;
import com.lvy.hczn.mq.rocket.ParamInfo;
import com.lvy.hczn.mq.rocket.ProducerUtil;
import com.lvy.hczn.transmit.domain.dto.cteck.DeliveryOrderInfo;
import com.lvy.hczn.transmit.domain.dto.cteck.DeliveryOrderInfoDetail;
import com.lvy.hczn.transmit.service.TAccessManagerService;
import com.lvy.hczn.transmit.service.TDeliveryOrderInfoService;
import com.lvy.hczn.transmit.service.TTransportService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TTransportServiceImpl implements TTransportService {

    @Autowired
    private WarehouseService warehouseService;

    @Autowired
    private ProducerUtil producerUtil;

    @Autowired
    private TDeliveryOrderInfoService tDeliveryOrderInfoService;

    @Autowired
    private TAccessManagerService tAccessManagerService;

    /**
     * 运输单推送到wms
     *
     * @param request
     * @param info
     * @return void
     * @author yw
     * @date 2023-08-26 20:51:38
     */
    @Override
    public void syncTransportFromPlatform(HttpServletRequest request, ParamInfo info) {
        if (info != null && info.getData() != null) {
            Transport transport = JSON.parseObject(JSON.toJSONString(info.getData()), Transport.class);
            transport.setDelFlag(transport.getIsDelete());
            log.error("syncTransportFromPlatform:{}", JSON.toJSONString(transport));

            if (transport.getDetailList() == null || transport.getDetailList().isEmpty()) {
                throw new UtilException("运输详情信息为空");
            }

            //过滤送货到供应商，只获取仓库
            List<TransportDetail> detailList = transport.getDetailList().stream().filter(item -> item.getArriveType().equals(Constants.TRANSPORT_ARRIVE_TYPE_ZERO)).collect(Collectors.toList());

            //详情列表根据仓库分组
            LinkedHashMap<String, List<TransportDetail>> detailMap = detailList.stream().collect(Collectors.groupingBy(TransportDetail::getArriveCode, LinkedHashMap::new, Collectors.toList()));

            detailMap.forEach((targetWarehouseCode, transportDetails) -> {
                Warehouse targetWarehouse = warehouseService.getOne(Wrappers.<Warehouse>lambdaQuery().eq(Warehouse::getWarehouseCode, targetWarehouseCode).last("limit 1"));
                if (ObjUtil.isNotNull(targetWarehouse)) {
                    // 生成目标送货仓库门禁
                    access(transport, Constants.ACCESS_TYPE_THREE, targetWarehouseCode);

                    // 遍历货箱列表生成采购单
                    initTransportPurchaseOrder(transportDetails,transport,targetWarehouse);
                }

//                String topic = warehouseService.selectRegionAreaTopic(warehouse);
//                ParamInfo<Transport> paramInfo = new ParamInfo<>();
//                transportInfo.setDetailList(valueWarehouse);
//                paramInfo.setData(transportInfo);
//                String tag = warehouse.getWarehouseCode() + "_" + MqConstants.TOPIC_TRANSPORT_TAG;
//                try {
//                    producerUtil.sendAsyncMsg(topic, tag, JSON.toJSONString(paramInfo).getBytes(StandardCharsets.UTF_8), IdUtil.fastSimpleUUID());
//                } catch (Exception e) {
//                    throw new UtilException("信息发送异常");
//                }
            });
        }
    }

    /**
     * 根据TransportDetail分组，字段所属出库还是入库，走不同的数据初始化
     *
     * @param transportDetailList
     * @param transport
     * @param warehouse
     * @return void
     * @author yw
     * @date 2023-08-27 18:31:11
     */
//    public void groupingByType(List<TransportDetail> transportDetailList, Transport transport, Warehouse warehouse) {
//        LinkedHashMap<Integer, List<TransportDetail>> typeMap = transportDetailList.stream().collect(Collectors.groupingBy(TransportDetail::getType, LinkedHashMap::new, Collectors.toList()));
//        if (typeMap.containsKey(Constants.TRANSPORT_DETAIL_TYPE_ONE)) {
//            //入库
//            initTransportPurchaseOrder(typeMap.get(Constants.TRANSPORT_DETAIL_TYPE_ONE), transport, warehouse);
//        }
//        if (typeMap.containsKey(Constants.TRANSPORT_DETAIL_TYPE_ZERO)) {
//            //出库
//            initTransportOutbound(typeMap.get(Constants.TRANSPORT_DETAIL_TYPE_ZERO), transport, warehouse);
//        }
//        access(transport, Constants.ACCESS_TYPE_THREE, warehouse.getWarehouseCode(), transportDetailList.get(0));
//    }

    /**
     * 门禁
     *
     * @param transport
     * @param type
     * @param warehouseCode
     * @return void
     * @author yw
     * @date 2023-06-04 17:09:22
     */
    public void access(Transport transport, Integer type, String warehouseCode) {
        AccessManager accessManager = new AccessManager();
        ParamInfo<AccessManager> paramInfo = new ParamInfo<>();
        paramInfo.setWarehouseCode(warehouseCode);
        accessManager.setSourceCode(transport.getTransportCode());
        accessManager.setAccessCode(transport.getTransportCode());
        accessManager.setRemark(transport.getId());
        accessManager.setType(type);
        paramInfo.setData(accessManager);
        tAccessManagerService.syncBoxLeasePlatform(paramInfo);
    }

    /**
     * 仓库运输单出库数据初始化
     *
     * @param transportDetailList
     * @param transport
     * @param warehouse
     * @return void
     * @author yw
     * @date 2023-08-27 18:59:31
     */
//    public void initTransportOutbound(List<TransportDetail> transportDetailList, Transport transport, Warehouse warehouse) {
//        TransportDetail transportDetail = transportDetailList.get(0);
//        List<OutboundOrderDetail> outboundOrderDetailList = new ArrayList<>();
//        List<WarehousingEntry> entryList = new ArrayList<>();
//        OutboundOrder outboundOrder = new OutboundOrder();
//        outboundOrder.setId(transportDetail.getId());
//        outboundOrder.setOutboundOrderCode(transport.getTransportCode());
//        outboundOrder.setOutboundOrderType(Constants.OUTBOUND_ORDER_TYPE_FOUR);
//        outboundOrder.setServiceCode(transportDetail.getServiceCode());
//        outboundOrder.setServiceType(transportDetail.getServiceType());
//        outboundOrder.setWarehouseCode(warehouse.getWarehouseCode());
//        outboundOrder.setSourceId(transport.getId() + Constants.SOURCE_ID_DEFAULT + transport.getTransportCode());
//        outboundOrder.setOutWithBox(2);
//        outboundOrder.setExpressId(transport.getDeliveryUserId());
//        outboundOrder.setWeight(BigDecimal.ZERO);
//        outboundOrder.setCount(0);
//        transportDetailList.forEach(detail -> {
//            detail.getDetailGoods().forEach(transportDetailGoods -> {
//                OutboundOrderDetail outboundOrderDetail = new OutboundOrderDetail();
//                outboundOrderDetail.setId(transportDetailGoods.getId());
//                outboundOrderDetail.setWarehouseCode(warehouse.getWarehouseCode());
//                outboundOrderDetail.setSourceId(outboundOrder.getSourceId() + transportDetailGoods.getId());
//                outboundOrderDetail.setOutboundOrderCode(outboundOrder.getOutboundOrderCode());
//                outboundOrderDetail.setBoxCode(transportDetailGoods.getCartonCode());
//                outboundOrderDetail.setGoodsBoxSpecId(transportDetailGoods.getContainerId());
//                outboundOrderDetail.setBatchCode(outboundOrder.getOutboundOrderCode());
//                outboundOrderDetail.setSaleOrderCode(outboundOrder.getServiceCode());
//                outboundOrderDetail.setDataType(transportDetailGoods.getDataType());
//                outboundOrderDetail.setGoodsCode(transportDetailGoods.getMerchandiseCode());
//                outboundOrderDetail.setSpuCode(transportDetailGoods.getMerchandiseCode());
//                outboundOrderDetail.setSkuCode(transportDetailGoods.getMerchandiseSku());
//                outboundOrderDetail.setSpecCode(transportDetailGoods.getMerchandiseSpecif());
//                outboundOrderDetail.setWeight(transportDetailGoods.getMerchandiseWeight());
//                outboundOrderDetail.setNumber(transportDetailGoods.getMerchandiseTfNum());
//                outboundOrderDetail.setUnit(transportDetailGoods.getMerchandiseUnit());
//                outboundOrderDetail.setStatus(Constants.OUTBOUND_DETAIL_STATUS_ZERO);
//                outboundOrderDetailList.add(outboundOrderDetail);
//                initWarehousingEntry(entryList, outboundOrderDetail, transportDetailGoods, outboundOrder, transport, detail);
//            });
//        });
//        outboundOrder.setList(outboundOrderDetailList);
//        String topic = warehouseService.selectRegionAreaTopic(warehouse);
//        String tagOut = warehouse.getWarehouseCode() + "_" + MqConstants.TOPIC_TRANSPORT_TAG_OUT;
//        ParamInfo paramInfo = new ParamInfo<>();
//        paramInfo.setData(outboundOrder);
//        try {
//            producerUtil.sendAsyncMsg(topic, tagOut, JSON.toJSONString(paramInfo).getBytes(StandardCharsets.UTF_8), IdUtil.fastSimpleUUID());
//        } catch (Exception e) {
//            throw new UtilException("信息发送异常");
//        }
//
//        if (!entryList.isEmpty()) {
//            ParamInfo<WarehousingEntry> paramInfoEntry = new ParamInfo<>();
//            paramInfoEntry.setList(entryList);
//            String tagEntry = warehouse.getWarehouseCode() + "_" + MqConstants.TOPIC_WAREHOUSE_ENTRY;
//            try {
//                producerUtil.sendAsyncMsg(topic, tagEntry, JSON.toJSONString(paramInfoEntry).getBytes(StandardCharsets.UTF_8), IdUtil.fastSimpleUUID());
//            } catch (Exception e) {
//                throw new UtilException("信息发送异常");
//            }
//        }
//    }
//
//    public void initWarehousingEntry(List<WarehousingEntry> entryList, OutboundOrderDetail outboundOrderDetail, TransportDetailGoods transportDetailGoods, OutboundOrder outboundOrder, Transport transport, TransportDetail transportDetail) {
//        WarehousingEntry warehousingEntry = new WarehousingEntry();
//        warehousingEntry.setEntryCode(outboundOrder.getOutboundOrderCode());
//        warehousingEntry.setServiceCode(outboundOrder.getServiceCode());
//        warehousingEntry.setWarehouseCode(outboundOrder.getWarehouseCode());
//        warehousingEntry.setDataType(transportDetailGoods.getDataType());
//        warehousingEntry.setBoxCode(transportDetailGoods.getCartonCode());
//        warehousingEntry.setSourceId(outboundOrder.getSourceId());
//        warehousingEntry.setServiceType(outboundOrder.getServiceType());
//        warehousingEntry.setOrderType(2);
//        warehousingEntry.setSpuId(outboundOrderDetail.getGoodsCode());
//        warehousingEntry.setSpecCode(outboundOrderDetail.getSpecCode());
//        warehousingEntry.setSkuCode(outboundOrderDetail.getSkuCode());
//        warehousingEntry.setWarrantyDate(transportDetailGoods.getWarrantyDate());
//        warehousingEntry.setPrice(BigDecimal.ONE);
//        warehousingEntry.setQuantity(outboundOrderDetail.getNumber());
//        warehousingEntry.setWeight(outboundOrderDetail.getWeight());
//        warehousingEntry.setPurchaserId("");
//        warehousingEntry.setUnit(outboundOrderDetail.getUnit());
//        warehousingEntry.setSupplierCode(transportDetailGoods.getSupplierCode());
//        warehousingEntry.setProducerId(transportDetailGoods.getProducerId());
//        if (transportDetailGoods.getProducerDate() != null && transportDetailGoods.getWarrantyDate() != null) {
//            warehousingEntry.setShelfLife(transportDetailGoods.getProducerDate().plusDays(transportDetailGoods.getWarrantyDate()));
//        }
//        warehousingEntry.setPickTime(transportDetailGoods.getProducerDate());
//        warehousingEntry.setBatchCode(outboundOrderDetail.getBatchCode());
//        warehousingEntry.setProvenance("");
//        warehousingEntry.setStatus("0");
//        warehousingEntry.setNumberOfPerBox(outboundOrderDetail.getNumber());
//        warehousingEntry.setWeightOfPerBox(transportDetailGoods.getMerchandiseWeight());
//        entryList.add(warehousingEntry);
//    }

    /**
     * 仓库运输单入库数据初始化
     *
     * @param transportDetailList
     * @param transport
     * @param warehouse
     * @return void
     * @author yw
     * @date 2023-08-27 18:48:30
     */
    public void initTransportPurchaseOrder(List<TransportDetail> transportDetailList, Transport transport, Warehouse warehouse) {
        PurchaseOrder purchaseOrder = new PurchaseOrder();
        List<PurchaseOrderDetail> list = new ArrayList<>();
        List<GoodsBox> boxCodeList = new ArrayList<>();

        Set<String> sourceWarehouseCodes = new HashSet<>();

        TransportDetail transportDetail = transportDetailList.get(0);
        purchaseOrder.setWarehouseCode(warehouse.getWarehouseCode());
//        purchaseOrder.setSupplierCode(deliveryOrderInfo.getPickup());
        purchaseOrder.setDeliveryCode(transport.getTransportCode());
        purchaseOrder.setPurchaseOrderCode(transport.getTransportCode());
        purchaseOrder.setServiceCode(transportDetail.getServiceCode());
        purchaseOrder.setServiceType(transportDetail.getServiceType());
        purchaseOrder.setSourceId(transport.getId() + Constants.SOURCE_ID_DEFAULT + purchaseOrder.getPurchaseOrderCode());

        purchaseOrder.setDeliveryWay("2");
        purchaseOrder.setDeliveryType(2);
        purchaseOrder.setPurchaseSource("0");
        purchaseOrder.setConfirmStatus("1");
        purchaseOrder.setDeliveryTime(LocalDateTimeUtil.of(transport.getAppointPickupTime()));
        purchaseOrder.setDeliveryStatus("0");
        purchaseOrder.setDistributionCost(transport.getDeliveryFee());
        purchaseOrder.setPrice(BigDecimal.ZERO);
        purchaseOrder.setCreateBy(transport.getCreateBy());
        purchaseOrder.setRemark(transport.getRemark());

        for (TransportDetail transportDetailInfo : transportDetailList) {
            transportDetailInfo.getCartons().forEach(carton -> {
                sourceWarehouseCodes.add(carton.getArriveCode());

                PurchaseOrderDetail purchaseOrderDetail = new PurchaseOrderDetail();
                purchaseOrderDetail.setSpuId(carton.getMerchandiseCode());
                purchaseOrderDetail.setPurchaseOrderCode(purchaseOrder.getPurchaseOrderCode());
                purchaseOrderDetail.setBoxCode(carton.getCartonCode());
                purchaseOrderDetail.setBatchCode(purchaseOrder.getPurchaseOrderCode());
                purchaseOrderDetail.setSourceId(purchaseOrder.getSourceId() + carton.getId());

                //purchaseOrderDetail.setSpecCode(item.getMerchandiseSpecif());
                //平台现在的sku=spec,MerchandiseSpecif可能是中文
                if (purchaseOrder.getSourceId().endsWith(Constants.SOURCE_ID_DEFAULT + purchaseOrder.getPurchaseOrderCode())) {
                    purchaseOrderDetail.setSpecCode(carton.getMerchandiseCode());
                } else {
                    purchaseOrderDetail.setSpecCode(carton.getMerchandiseSpecif());
                }

                purchaseOrderDetail.setPrice(BigDecimal.ZERO);
                purchaseOrderDetail.setSkuCode(carton.getMerchandiseCode());
                purchaseOrderDetail.setWeight(carton.getMerchandiseWeight());
                purchaseOrderDetail.setPurchaseWeight(carton.getMerchandiseWeight());
                purchaseOrderDetail.setQuantity(carton.getMerchandiseNum());
                purchaseOrderDetail.setPurchaseQuantity(carton.getMerchandiseNum());
                purchaseOrderDetail.setUnit(carton.getMerchandiseUnit());
                purchaseOrderDetail.setSupplierCode(carton.getSupplierCode());
                purchaseOrderDetail.setStatus("0");

                purchaseOrderDetail.setVolume(carton.getMerchandiseVolume());

                purchaseOrderDetail.setProduceDate(carton.getProducerDate());
                purchaseOrderDetail.setWarrantyDate(carton.getWarrantyDate());

                purchaseOrderDetail.setDataType(transportDetailInfo.getDataType());
                if(carton.getType().equals("1")){
                    purchaseOrderDetail.setDataType("BGRK");
                }

                purchaseOrderDetail.setNumberOfPerBox(0);
                purchaseOrderDetail.setProducerId(carton.getProducerId());
                purchaseOrderDetail.setWeightOfPerBox(BigDecimal.ZERO);
                list.add(purchaseOrderDetail);
                GoodsBox goodsBox = new GoodsBox();
                goodsBox.setBoxCode(purchaseOrderDetail.getBoxCode());
                goodsBox.setGoodsBoxSpecId(carton.getContainerId());
                boxCodeList.add(goodsBox);
            });
        }
        purchaseOrder.setList(list);

        log.error("initTransportPurchaseOrder:{}", JSON.toJSONString(purchaseOrder));

        DeliveryOrder deliveryOrder = new DeliveryOrder();
        List<WarehousingEntry> entryList = new ArrayList<>();

        tDeliveryOrderInfoService.generateDeliver(purchaseOrder, deliveryOrder, entryList);

        tDeliveryOrderInfoService.sendMsg(deliveryOrder, entryList, boxCodeList, warehouse, purchaseOrder);

        List<Warehouse> warehouseList = warehouseService.list(Wrappers.<Warehouse>lambdaQuery().in(Warehouse::getWarehouseCode,sourceWarehouseCodes));
        for (Warehouse sourceWarehouse : warehouseList) {
            access(transport, Constants.ACCESS_TYPE_THREE, sourceWarehouse.getWarehouseCode());
        }

    }
}
